package com.example.myapplication;

import com.example.myapplication.shortvideo.utils.GsonUtil;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author: rongfeng
 * @date: 2020/9/2
 * @description
 */
public class youdao {
    static volatile int index = 0;

    public static List<String> words;
    static ExecutorService pool;

    static volatile List<String> shibai = new ArrayList<>();

    public static void main(String[] args) {
        pool = Executors.newFixedThreadPool(5);
        words = new ArrayList<>(new ReadWords().start3());
        start();
    }

    public static void start() {
        for (int i = 0; i < 5; i++) {
            nextClass();
        }
    }


    public synchronized static void nextClass() {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                if (index < words.size()) {
                    String word = words.get(index);
                    String url = getUrl(word);
                    index++;
                    if (isExists(word)) {
                        nextClass();
                    } else {
                        new Query2().getDns(url, word);
                    }
                }
            }
        });

        if (index == words.size()) {
            System.out.println("失败 " + shibai.size());
            for (String word :
                    shibai) {
                System.out.println(word);
            }
        }

    }

    public static String getUrl(String word) {
        return "http://www.youdao.com/w/" + word + "/#keyfrom=dict2.top";
    }


    public static class Query2 {
        Word mWord = new Word();
        List<Trs> trs = new ArrayList<>();
        List<Wfs> mWfs = new ArrayList<>();

        public Query2() {
            mWord.setTrs(trs);
            mWord.setWfs(mWfs);
        }

        public void getDns(String url, String word) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    shibai.add(word);
                }

                @Override
                public void onResponse(Call call, @NotNull okhttp3.Response response) throws IOException {
                    if (response.body() != null) {
                        String html = response.body().string();

                        getUkphone(html);
                        getTrans(html);
                        getAdditional(html);

                        mWord.setWord(word);
                        if (mWord.getTrs().size() > 0) {
                            saveFile(mWord, word);
                        } else {
                            shibai.add(word);
                        }
                        nextClass();
                    }
                }
            });
        }


        public void getUkphone(String html) {
            String tag1 = "<span class=\"phonetic\">";
            String tag2 = "</span>";
            int index1 = html.indexOf(tag1);
            if (index1 > 0) {
                String html1 = html.substring(index1 + tag1.length());
                int last1 = html1.indexOf(tag2);
                String html2 = html1.substring(1, last1 - 1);
                mWord.setUkphone(html2);
                getUsphone(html1);
            }
        }

        public void getUsphone(String html) {
            String tag1 = "<span class=\"phonetic\">";
            String tag2 = "</span>";
            int index1 = html.indexOf(tag1);
            if (index1 > 0) {
                String html1 = html.substring(index1 + tag1.length());
                int last1 = html1.indexOf(tag2);
                String html2 = html1.substring(1, last1 - 1);
                mWord.setUsphone(html2);
            }
        }


        public void getTrans(String html) {
            String tag1 = "<div class=\"trans-container\">";
            String tag2 = "</ul>";
            int index1 = html.indexOf(tag1);
            if (index1 > 0) {

                String html1 = html.substring(index1 + tag1.length());
                int last1 = html1.indexOf(tag2);
                String html2 = html1.substring(0, last1).replaceAll(" ", "")
                        .replaceAll("<ul>", "")
                        .replaceAll("<li>", "")
                        .replaceAll("</li>", "");

                String[] array = html2.split("\n");

                for (String str : array) {
                    if (!str.equals("")) {
                        int index3 = str.indexOf(".");
                        String type = str.substring(0, index3 + 1);
                        String trans = str.substring(index3 + 1);
                        trs.add(new Trs(type, trans));
                    }
                }
            }
        }


        public void getAdditional(String html) {
            String tag1 = "<p class=\"additional\">[";
            String tag2 = "]</p>";
            int index1 = html.indexOf(tag1);
            if (index1 > 0) {
                String html1 = html.substring(index1 + tag1.length());
                int last1 = html1.indexOf(tag2);
                if (last1 > 0) {
                    String html2 = html1.substring(0, last1)
                            .replaceAll(" ", "");

                    String[] array = html2.split("\n");

                    boolean is = true;
                    Wfs wfs = null;
                    for (String str : array) {
                        if (!str.equals("")) {
                            if (is) {
                                is = false;
                                wfs = new Wfs();
                                wfs.setName(str);
                            } else {
                                is = true;
                                wfs.setValue(str);
                            }
                        }
                        if (wfs != null) {
                            mWfs.add(wfs);
                        }
                    }
                }
            }
        }
    }


    public static boolean isExists(String word) {
        File file = new File("D:\\word\\all\\" + word + ".json");
        return file.exists();
    }

    public static void saveFile(Word bean, String word) {
        if (bean == null) {
            return;
        }
        File file = new File("D:\\word\\all\\" + word + ".json");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            String json = GsonUtil.toJson(bean);
            System.out.println(json);
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(json);
            out.close();
        } catch (IOException e) {
            System.out.println(word);
            e.printStackTrace();
        }
    }


    public static class Wfs implements Serializable {
        private String name;

        private String value;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }
    }

    public static class Trs implements Serializable {

        public Trs(String pos, String tran) {
            this.pos = pos;
            this.tran = tran;
        }

        private String pos;

        private String tran;

        public void setPos(String pos) {
            this.pos = pos;
        }

        public String getPos() {
            return this.pos;
        }

        public void setTran(String tran) {
            this.tran = tran;
        }

        public String getTran() {
            return this.tran;
        }
    }

    public static class Word implements Serializable {

        private String word;

        private String usphone;

        private String ukphone;


        private List<Trs> trs;

        private List<Wfs> wfs;

        public String getWord() {
            return word;
        }

        public void setWord(String word) {
            this.word = word;
        }

        public void setUsphone(String usphone) {
            this.usphone = usphone;
        }

        public String getUsphone() {
            return this.usphone;
        }

        public void setUkphone(String ukphone) {
            this.ukphone = ukphone;
        }

        public String getUkphone() {
            return this.ukphone;
        }


        public List<Trs> getTrs() {
            return trs;
        }

        public void setTrs(List<Trs> trs) {
            this.trs = trs;
        }

        public void setWfs(List<Wfs> wfs) {
            this.wfs = wfs;
        }

        public List<Wfs> getWfs() {
            return this.wfs;
        }


    }


}
